package nettysocket;/**
 * Created by zhanghb on 2019/9/2.
 */

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Description
 * @Author Zhanghb
 * @Date
 */
@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接激活");
        // 若没有StringEncoder，则发送不出去字符串。
        ctx.writeAndFlush("hello,world! 你好,世界!");
        ctx.writeAndFlush("hello,world1! 你好,世界!");
        System.out.println("写入完成");
        Channel channel = ctx.channel();
        channel.writeAndFlush("写入完成");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("从客户端读取数据："+msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.warn( "发生错误，关闭链接。", cause);
        ctx.close();
    }
}

